package com.yvan.serverless.jdbc.util;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.yvan.platform.StringUtils;
import com.yvan.serverless.jdbc.DaoParam;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DaoExecuterInsertUtils {

    public static String getInsertAnySql(String tableName, List<Map<String, Object>> fieldAndValueList, String dbType) {
        if (StringUtils.isBlank(tableName)) {
            throw new RuntimeException("TableName cannot be empty");
        }
        if (fieldAndValueList == null || fieldAndValueList.size() == 0) {
            throw new RuntimeException("FieldAndValue cannot be empty");
        }
        int fieldCount = fieldAndValueList.get(0).size();
        List<String> fieldList = Lists.newArrayList();
        for (String key : fieldAndValueList.get(0).keySet()) {
            fieldList.add(key);
        }
        String sql = null;
        if ("mysql".equals(dbType)) {
            List<String> valueList = new ArrayList<>();
            for (int i = 0; i < fieldAndValueList.size(); i++) {
                List<String> values = new ArrayList<>();
                for (int j = 0; j < fieldCount; j++) {
                    values.add("?");
                }
                valueList.add("(" + Joiner.on(",").join(values) + ")");
            }
            String fieldSql = " (" + Joiner.on(",").join(fieldList) + ")";
            String valueSql = " values " + Joiner.on(",").join(valueList);
            sql = "insert into " + tableName + fieldSql + valueSql;
        } else if ("oracle".equals(dbType)) {
            List<String> valueList = new ArrayList<>();
            for (int i = 0; i < fieldAndValueList.size(); i++) {
                List<String> values = new ArrayList<>();
                for (int j = 0; j < fieldCount; j++) {
                    values.add("?");
                }
                if (i == 0) {
                    valueList.add("select " + Joiner.on(",").join(values) + " from dual");
                } else {
                    valueList.add("UNION ALL select " + Joiner.on(",").join(values) + " from dual");
                }
            }
            String fieldSql = " (" + Joiner.on(",").join(fieldList) + ")";
            String valueSql = " " + Joiner.on(" ").join(valueList);
            sql = "insert into " + tableName + fieldSql + valueSql;
        }

        return sql;
    }

    public static List<DaoParam> getInsertAnyParams(List<Map<String, Object>> fieldAndValueList) {
        List<DaoParam> values = Lists.newArrayList();
        for (Map<String, Object> entity : fieldAndValueList) {
            for (String key : entity.keySet()) {
                DaoParam param = new DaoParam(key, entity.get(key));
                values.add(param);
            }
        }
        return values;
    }


}
